<template>
  <!--编辑盘点  唐美莉 -->
  <section>
    <table
      border="0"
      width="100%"
      style="border-spacing: 0;border-collapse: collapse;"
    >
      <tr>
        <td>
          <el-form :inline="true">
            <el-form-item>
              <el-input
                v-model="form.vagueKey"
                clearable
                placeholder="商品名称"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                circle
                icon="el-icon-search"
                @click="getData(-1)"
              ></el-button>
            </el-form-item>
            <!-- <el-form-item>
              <el-button type="primary" :disabled="!qxBtns.add" plain @click="addDurg(null)">+添加</el-button>
            </el-form-item>-->
          </el-form>
        </td>
        <!-- <td style="text-align:right;vertical-align: top;">
          <el-button @click="exportExcel()" :disabled="!qxBtns.export" plain>导出</el-button>
        </td>-->
      </tr>
    </table>

    <table class="table-box">
      <thead>
        <tr>
          <th>商品名称</th>
          <th>规格</th>
          <th>单位</th>
          <th>生产厂商</th>
          <th>供应商</th>
          <th>批号</th>
          <th>有效期</th>
          <th>账面数量</th>
          <th style="width:200px;">实际数量</th>
          <th>盘盈盘亏</th>
          <th>描述</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in tableList" :key="index">
          <td>{{ item.goodsName }}</td>
          <td>{{ item.specs }}</td>
          <td>{{ item.residueNumUnit | changeAssist(dwList) }}</td>
          <td>{{ item.factory }}</td>
          <td>{{ item.supplierName }}</td>
          <td>{{ item.lotNumber }}</td>
          <td>{{ item.effectiveTime | changeTime }}</td>
          <td>{{ item | residueDurg(dwList) }}</td>
          <td style="width:300px;display:flex;">
            <el-input
              style="flex:1"
              @change="calculateActual(item, 1)"
              v-model.number="item.actualNum"
            >
              <template slot="append">{{
                item.residueNumUnit | changeAssist(dwList)
              }}</template>
            </el-input>
            <el-input
              style="flex:1"
              v-if="item.isPiece"
              @change="calculateActual(item, 2)"
              v-model.number="item.actualNumSubsection"
            >
              <template slot="append">{{
                item.residueNumSubsectionUnit | changeAssist(dwList)
              }}</template>
            </el-input>
            <!-- <el-input v-model.number="item.actualNum">
              <template slot="append">{{item.residueNumUnit | changeAssist(dwList)}}</template>
            </el-input> -->
          </td>
          <td :style="{ color: item.color }">
            <label v-if="item.type == 2">{{item.changeNum>0?'-':''}}</label>
            <label>{{ item.changeNum}}{{ item.residueNumUnit | changeAssist(dwList) }}</label>
            <label v-if="item.isPiece">{{ item.changeactualNum }}
              {{ item.residueNumSubsectionUnit | changeAssist(dwList) }}</label>
          </td>
          <td>
            <el-input
              type="textares"
              v-model="item.remark"
              maxlength="50"
              show-word-limit
            ></el-input>
          </td>
        </tr>
      </tbody>
    </table>
    <div
      v-if="tableList.length == 0"
      style="color:#999;padding:10px 0;text-align:center;"
    >
      <i class="iconfont iconwushuju" style="font-size:40px;"></i>
      <div>暂无数据</div>
    </div>
    <br />
    <pager v-model="pager" @change-pagenum="getData"></pager>
    <br />
    <el-row>
      <el-button type="primary" :loading="btnLoading" @click="onSubmit(1)"
        >保 存</el-button
      >
      <el-button type="promary" @click="onSubmit(2)">保 存 并 审 核</el-button>
      <el-button @click="onClose">取消</el-button>
    </el-row>
    <!-- <set v-model="dialogEdit" :curItem="curItem" @success="getData"></set> -->
  </section>
</template>
<script>
import Excel from "@/_js/excel.js";
export default {
  name: "storageList",
  data() {
    return {
      dialogJoin: false,
      dialogEdit: false,
      curItem: null,
      btnLoading: false,
      pager: { pageSize: 10, pageNum: 1, total: 0 },
      tableList: [],
      form: {
        saveType: 1,
        id: "",
        vagueKey: "",
        type: 1,
        numType:1 
      },
      isMonth: 0,
      dwList: [],
      qxBtns: {},
      dataList: [],
      distype: "2",
      setType: "1",
    };
  },
  created() {
    this.form.hpId = this.adminUser.hpId;
    this.isMonth = this.$route.query.type;
    this.getQX();
    this.getData();
    this.getBasic();
  },
  methods: {
    getData(type) {
      let th = this;
      if (type == -1) {
        th.pager.pageNum = 1;
        th.pager.total = 0;
      }
      let j = { id: "", type: 1, queryStr: "", source: 1,numType:1 };
      j = Object.assign(j, th.pager);
      j = Object.assign(j, th.form);
      j.queryStr = th.form.vagueKey;
      th.showLoading();
      let id = th.jieMi(th.$route.query.id);
      if (id != 0) {
        j.id = id;
        th.$api.findMedicalInventoryItemPageV2(j).then((res) => {
          if (res.executed) {
            let _tableList = res.dataBody.list;
            _tableList.map((it) => {
              // it.usableNum = it.actualNum * it.preparationNum + it.actualSubNum;
              //计算药品使用数量
              it.usableNum = it.actualNum * it.preparationNum + it.actualSubNum;
              //药品拆零小单位
              if (!it.residueNumUnit) {
                it.residueNumUnit = it.totalQuantityUnit;
              }
              //药品数量（大）
              if (!it.residueNum) {
                it.residueNum = it.totalQuantity;
              }
              //药品数量（小）
              it.preparationNum = it.preparationNum;
              it.actualNumSubsection = it.actualSubNum;
              it.residueNum = it.actualNum;
              it.residueNumSubsection = it.actualSubNum;
              it.residueNumSubsectionUnit = it.actualSubNumUnit;
              let totalActualNum=it.currentNum;
              it.changeNum = Math.floor(
                Number(it.usableNum-totalActualNum) / it.preparationNum
              );
              it.changeactualNum = Math.floor(
                Number(it.usableNum-totalActualNum) % it.preparationNum
              );
              for (let i = 0; i < th.dataList.length; i++) {
                if (th.dataList[i].id == it.id) {
                  it.changeactualNum = th.dataList[i].actualNumSubsection;
                  it.actualNum = th.dataList[i].actualNum;
                  it.changeNum = th.dataList[i].changeNum;
                }
              }
              it.color = it.type !== 3 ? "#f91616" : "";
            });
            th.tableList = _tableList;
            th.pager.total = res.dataBody.total;
          }
          th.showLoading(false);
        });
      } else {
        th.$api.pageStockBatchV2(j).then((res) => {
          if (res.executed) {
            if (res.dataBody != undefined) {
              let list = [];
              let arr = res.dataBody.list;
              arr.map((it) => {
                it.batchId = it.id;
                it.currentNum = it.residueNum;
                it.remark = "";
                it.changeNum = 0;
                it.changeactualNum = 0;
                it.actualNum = it.residueNum;
                it.actualNumSubsection = it.residueNumSubsection;
                for (let i = 0; i < th.dataList.length; i++) {
                  if (th.dataList[i].id == it.id) {
                    it.changeactualNum = th.dataList[i].actualNumSubsection;
                    it.actualNum = th.dataList[i].actualNum;
                    it.changeNum = th.dataList[i].changeNum;
                    if (it.changeNum < 0) {
                      it.type = 2;
                    }
                  }
                }
                // if (it.changeNum < 0) {
                //   it.type = 2;
                // }
                it.color = it.type == 2 ? "#f91616" : "";
              });
              th.tableList = arr;
              th.pager.total = res.dataBody.total;
            } else {
              th.tableList = [];
              th.pager.total = 0;
            }
          }
          th.showLoading(false);
        });
      }
    },
    calculateActual(item, type) {
      let intRsg = /^\d+$/;
      if (!intRsg.test(item.actualNum)) {
        item.actualNum = Number(item.residueNum);
      }
      if (!intRsg.test(item.actualNumSubsection)) {
        item.actualNumSubsection = Number(item.residueNumSubsection);
      }
      let ls = this.dataList;
      //计算账面总数
      let totalNum = 0;
      if (item.usableNum) {
        totalNum = item.currentNum;
      } else {
        totalNum = item.preparationNum * item.residueNum + item.residueNumSubsection;
      }
      //计算实际总数
      console.log(item.actualNum);
      console.log(item.actualNumSubsection);
      let totalActualNum = item.actualNum * item.preparationNum + item.actualNumSubsection;
      item.changeNum = parseInt(
        Number(totalActualNum - totalNum) / item.preparationNum
      );
      item.changeactualNum = Math.floor(
        Number(totalActualNum - totalNum) % item.preparationNum
      );
      item.type = item.changeNum <0 ? 2:3;
      if (totalActualNum < totalNum) {
        item.isthan = true;
        item.color = "#f91616";
      } else {
        item.isthan = false;
        item.color = "#f91616";
      }
      for (let i = 0; i < ls.length; i++) {
        if (ls[i].id == item.id) {
          this.dataList.splice(i, 1);
        }
      }
      this.dataList.push(item);
    },
    onSubmit(type) {
      let th = this;
      if (th.dataList.length < 0) {
        th.$message.warning("请填写您需要修改的库存");
        return;
      }
      th.form.saveType = type;
      let id = th.jieMi(th.$route.query.id);
      th.form.id = id;
      let json = {
        medicalInventory: "",
        medicalInventoryItem: "",
      };
      th.btnLoading = true;
      json.medicalInventory = JSON.stringify(th.form);
      let list = th.dataList;
      let _datalist = [];
      list.map((it) => {
        let arr = {};
        arr.actualNumSubsection = it.actualNumSubsection;
        arr.id = it.id;
        arr.batchId = it.batchId;
        arr.goodsId = it.goodsId;
        arr.actualNum = it.actualNum;
        arr.remark = it.remark;
        _datalist.push(arr);
      });
      json.medicalInventoryItem = JSON.stringify(_datalist);
      if (id != 0) {
        th.$api
          .updateMedicalInventoryV2(json)
          .then((res) => {
            if (res.executed) {
              th.$message.success("保存成功");
              th.onClose();
            } else {
              th.$message.success(res.message);
            }
            th.btnLoading = false;
          })
          .catch((res) => {
            th.btnLoading = false;
          });
      } else {
        th.$api
          .addMedicalInventoryV2(json)
          .then((res) => {
            if (res.executed) {
              th.$message.success("保存成功");
              th.onClose();
            } else {
              th.$message.success(res.message);
            }
            th.btnLoading = false;
          })
          .catch((res) => {
            th.btnLoading = false;
          });
      }
    },
    getBasic() {
      let th = this;
      th.getCommonConfigByKey("药品剂量单位").then((res) => {
        th.dwList = res;
      });
    },
    onClose() {
      let th = this;
      th.$router.push({
        path: "/page/drugIndex",
        query: th.getUrlToken({ id: th.jiaMi(4) }),
      });
    },
  },
  components: {},
};
</script>
